<?php

namespace App\Http\Controllers\Wechat;

use App\Http\Controllers\Controller;
use App\Http\Requests\AddressAuth;
use App\Models\Address;
use App\Models\Region;
use Illuminate\Http\Request;


class AddressController extends Controller
{
    // 地址列表
    public function index()
    {
        $list = Address::whereUserId(auth('wechat')->id())
            ->limit(20)
            ->get();
        return $this->writeJson(0, $list);
    }

    // 地址-新增/编辑
    public function add(AddressAuth $request)
    {
        if ($id = $request->post('id')) {
            $model = Address::whereUserId(auth('wechat')->id())
                ->where('id', $id)
                ->first();
            if (empty($model)) {
                return $this->writeJson(500, null, '数据不存在');
            }
        } else {
            $model = new Address();
            $model->user_id = auth('wechat')->id();
        }

        $model->name = $request->post('name');
        $model->phone = $request->post('phone');
        $model->province_id = $request->post('province_id');
        $model->city_id = $request->post('city_id');
        $model->area_id = $request->post('area_id');
        $model->detail = $request->post('detail');
        $model->id_default = $request->post('id_default') ? 1 : 0;
        $model->province_name = Region::whereId($model->province_id)->value('name');
        $model->city_name = Region::whereId($model->city_id)->value('name');
        $model->area_name = Region::whereId($model->area_id)->value('name');
        $model->save();

        return $this->writeJson(0, null, '保存成功');
    }

    // 删除地址
    public function del(Request $request)
    {
        $id = $request->post('id');
        if (empty($id)) {
            return $this->writeJson(500, null, '参数错误');
        }

        $address = Address::whereUserId(auth('wechat')->id())
            ->where('id', $id)
            ->first();
        if (empty($address)) {
            return $this->writeJson(500, null, '数据不存在');
        }

        $address->delete();
        return $this->writeJson(0, null, '删除成功');
    }
}
